'use strict';

const Controller = require('egg').Controller;


class contrl extends Controller {
  async loginPage(){
    const {ctx} = this;
    await ctx.render("login.ejs");
  }
  async registerPage(){
    const {ctx} = this;
    await ctx.render("register.ejs");
  }
  async register() {
    const { ctx ,service,app} = this;
    var opt = ctx.request.body;
    const rule = { tel: 'tel',password:"password" };
    try{
      ctx.validate(rule, opt);
      let res = await service.user.register(opt);
      ctx.success(res);
    }catch(e){
      ctx.error(app.resCode.params,e.message || e);
    }
  }
  async login(){
    const { ctx ,service,app} = this;
    var opt = ctx.request.body;
    const rule = { tel: 'tel',password:"password" };
    try{
      ctx.validate(rule, opt);
      let res = await service.user.login(opt);
      ctx.session.userinfo = res;
      ctx.success(res);
    }catch(e){
      ctx.error(app.resCode.params,e.message || e);
    }
  }
  async update(){

  }
  async delete(){

  }
  async findOne(){
    //获取他人的用户信息
    const {ctx,app} = this;
    //let userid = ctx.params.id;
    let userid = ctx.query.id;
    if(userid){
      let res = await ctx.service.user.findOne(userid);
      ctx.success(res);
    }else{
      ctx.error(app.resCode.params);
    }
  }
  async info(){
    //获取自己的用户信息
    const {ctx,app} = this;
    ctx.success(ctx.session.userinfo);
  }
  async loginout(){
    const {ctx,app} = this;
    ctx.session.userinfo = null;
    ctx.success();
  }
  async test(){
    const {ctx,app} = this;
      const rule = { tel: 'tel' };
      try{
        ctx.validate(rule, ctx.query);
        ctx.success({
          tel:ctx.query.tel
        });
      }catch(e){
        ctx.error(app.resCode.login,e.message);
      }
  }
}

module.exports = contrl;
